package net.lovesrc.allin;

import com.zhouzhou.fastjava.BizException;
import net.lovesrc.allin.biz.NotificationService;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@RestController
public class ExceptionAdviceController {

    @Autowired
    private Environment environment;

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdviceController.class);

    @Autowired
    private NotificationService notificationAdminService;

    @ExceptionHandler(value = {BizException.class})
    public Message BizException(BizException e) {

        return Message.failure(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = {ClientAbortException.class, HttpRequestMethodNotSupportedException.class})
    public Message ignoreException(Exception e) {

        return Message.failure("IGNORE", e.getMessage());
    }

    @ExceptionHandler(value = {Exception.class})
    public Message ApiException(Exception e) {

        logger.error(e.getMessage(), e);
        String message = e.getMessage();
        if (message.contains("ConstraintViolationException")) {
            return Message.failure("100", "操作失败，有重复数据");
        }
        String url = "";
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest servletRequest = requestAttributes.getRequest();
            url = servletRequest.getRequestURL().toString();
        } catch (Exception ex) {
            logger.error("Get Url Errro", ex);
        }
        if (environment.acceptsProfiles("live")) {
            notificationAdminService.email("504958845@qq.com", url, ExceptionUtils.getStackTrace(e));
        }
        return Message.failure("ERROR", e.getMessage());
    }

}
